import React from 'react';
import { View } from '@tarojs/components';
import './index.less';
import { getEnv } from '@tarojs/taro';
import { useRecoilValue } from 'recoil';
import { useUserModel } from '@/models/useUserModel';
import type { UserModelType } from '@/models/useUserModel';

import { eventsBus } from '@vh-mobile/pro-utils';
import { checkPermissionAuth } from '../../access';

declare type AuthCustomType = {
  /**
   * 需要限制权限的按钮或者内容
   */
  children: React.ReactNode;
  /**
   * 自定义的父级的className
   */
  className?: string;
  /**
   * 页面需要的显示的权限ID
   */
  accessId?: number | string;
};

export const isAuth = (userModel: UserModelType | undefined) => {
  // 用户未登录
  if (!userModel) {
    if (getEnv() === 'WEAPP') {
      eventsBus.$pageTrigger('SetShowLogin', true);
    }
    return false;
  }

  return true;
};

const AuthCustom = (Props: AuthCustomType) => {
  const userModel = useRecoilValue(useUserModel);
  const { className, accessId } = Props;

  const handlerClick = () => {
    isAuth(userModel);
  };

  return (
    <View className={`auth-wrapper-custom ${className ? className : ''}`}>
      {accessId ? (
        checkPermissionAuth(userModel, accessId) ? (
          Props.children
        ) : (
          <></>
        )
      ) : (
        Props.children
      )}
      {!userModel && (
        <>
          <View className="auth-modal" onClick={handlerClick} />
        </>
      )}
    </View>
  );
};

export default AuthCustom;
